package com.itheima.wemedia.service.impl;

import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.AppJwtUtil;
import com.itheima.wemedia.pojo.WmUser;
import com.itheima.wemedia.mapper.WmUserMapper;
import com.itheima.wemedia.service.WmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @description <p>自媒体用户信息 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.wemedia.service.impl
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    /**
     * 通appUserId查询自媒体账号信息
     *
     * @param appUserId
     * @return
     */
    @Override
    public WmUser getByAppUserId(Integer appUserId) {
        WmUser wmUser = query().eq("ap_user_id", appUserId).one();
        return wmUser;
    }

    /**
     * 登录校验
     *
     * @param paramMap
     * @return
     */
    @Override
    public Map<String, Object> loginCheck(Map<String, String> paramMap) {
        //1. 参数校验
        String name = paramMap.get("name");
        String password = paramMap.get("password");
        if(StringUtils.isEmpty(name) || StringUtils.isEmpty(password)){
            throw new LeadNewsException("用户名或密码不能为空!");
        }
        //2. 通过用户名查询用户信息
        WmUser wmUser = query().eq("name", name).one();
        //3. 如果不存在用户则报错
        if(null == wmUser){
            throw new LeadNewsException("用户名或密码错误");
        }
        //4. 获取盐与前端密码拼接后加密
        password = password + wmUser.getSalt();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //5. 比较密码
        if(!wmUser.getPassword().equals(password)) {
            //6. 密码不相同则报错
            throw new LeadNewsException("用户名或密码错误");
        }
        //7. 相同，则生成token
        String token = AppJwtUtil.createToken(wmUser.getId().longValue());
        //8. 构建map返回
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("token", token);
        resultMap.put("user", wmUser);
        return resultMap;
    }
}
